import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
# 数据分离
from sklearn.model_selection import train_test_split

# 建立顺序的MLP模型
from keras.models import Sequential
from keras.layers import Dense, Activation

from sklearn.metrics import accuracy_score

# 加载数据
data = pd.read_csv('data.csv')
# print(笔记.md.head())

# 数据分离
X = data.drop(['y'], axis=1)
Y = data.loc[:, 'y']
# print(X.head(),Y.head())

# 可视化
# fig1 = plt.figure(figsize=(10, 10))
# passed = plt.scatter(X.loc[:, 'x1'][Y == 1], X.loc[:, 'x2'][Y == 1])
# failed = plt.scatter(X.loc[:, 'x1'][Y == 0], X.loc[:, 'x2'][Y == 0])
# plt.legend((passed, failed), ('passed', 'failed'))
# plt.xlabel('x1')
# plt.ylabel('x2')
# plt.title('raw 笔记.md')
# plt.show()

# 数据分离(分开训练集和测试集)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=10)
# print(X.shape, X_train.shape, X_test.shape)

# 建立模型
MLP_model = Sequential()
MLP_model.add(Dense(units=20, input_dim=2, activation='sigmoid'))
MLP_model.add(Dense(units=1, activation='sigmoid'))
MLP_model.summary()

# 配置模型训练参数
MLP_model.compile(loss='binary_crossentropy', optimizer='adam')

# 模型训练
# verbose：日志显示，0为不在标准输出流输出日志信息，1为输出进度条记录，2为每个epoch输出一行记录
MLP_model.fit(X_train, Y_train, epochs=8000,verbose=0)  # epochs 迭代次数

# 计算模型预测准确率
y_train_predict = (MLP_model.predict(X_train) > 0.5).astype(int)
# y_train_predict = (MLP_model.predict(X_train) > 0.5).astype(int)
accuracy_train = accuracy_score(Y_train, y_train_predict)
print("训练集准确率：", accuracy_train)

y_test_predict = (MLP_model.predict(X_test) > 0.5).astype(int)
# y_test_predict = np.argmax(y_test_predict, axis=1)
accuracy_test = accuracy_score(Y_test, y_test_predict)
print("测试集准确率：", accuracy_test)

# 格式转换
y_train_predict_from = pd.Series(i[0] for i in y_train_predict)
# print(y_train_predict_from)

# 可视化
xx, yy = np.meshgrid(np.arange(0, 1, 0.01), np.arange(0, 1, 0.01))
x_range = np.c_[xx.ravel(), yy.ravel()]
y_range_predict = (MLP_model.predict(x_range) > 0.5).astype(int)
y_range_predict_from = pd.Series(i[0] for i in y_range_predict)

fig2 = plt.figure(figsize=(10, 10))
passed_predict = plt.scatter(x_range[:, 0][y_range_predict_from == 1], x_range[:, 1][y_range_predict_from == 1])
failed_predict = plt.scatter(x_range[:, 0][y_range_predict_from == 0], x_range[:, 1][y_range_predict_from == 0])
passed = plt.scatter(X.loc[:, 'x1'][Y == 1], X.loc[:, 'x2'][Y == 1])
failed = plt.scatter(X.loc[:, 'x1'][Y == 0], X.loc[:, 'x2'][Y == 0])
plt.legend((passed, failed, passed_predict, failed_predict), ('passed', 'failed', 'passed_predict', 'failed_predict'))
plt.xlabel('x1')
plt.ylabel('x2')
# plt.title('笔记.md')
# plt.show()
plt.savefig('k2.png')